/**
 * 通用的数据处理和验证类 
 
	1、在main.js中配置下列代码
	import Utils from '@/utils/utils.js';
	Vue.prototype.$Utils = Utils;
	
	2、使用方式
	
	let str = "0";
	if(this.$Utils.isNull(str)){
		console.log("str 是空")
	}
 */
export default class Utils {
	/**
	 * 检查是否为空数组 空数组返回 true
	 * @param {Array} arr 数组
	 * @return Boolean
	 */
	static isEmptyArr(arr) {
		if (!Array.isArray(arr)) throw new Error('isEmptyArr 参数不是一个数组');
		if (!arr.length) return true;
		return false;
	}
 
	/**
	 * 是否是空  不为空false 为空true
	 * @param {any} opt 验证参数
	 * @return Boolean
	 */
	static isNull(opt) {
		if (opt == '' || opt == null || opt == 'null' || opt == undefined) return true;
		return false;
	}
 
	/**
	 * 校验密码
	 * @param phone
	 * @returns {boolean}
	 */
	static checkPassword(phone) {
		let reg = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/;
		return reg.test(phone);
	}
 
	/**
	 * 校验手机号格式
	 * @param phone
	 * @returns {boolean}
	 */
	static checkPhone(phone) {
		let reg = /^1[3-9]\d{9}$/;
		console.log(reg.test(phone));
		return reg.test(phone);
	}
 
	/**
	 * 校验邮箱格式
	 * @param email
	 * @returns {boolean}
	 */
	static checkEmail(email) {
		let reg = /^\w+@[a-z0-9]+\.[a-z]{2,4}$/;
		return reg.test(email);
	}
 
	/**
	 * 校验身份证号格式
	 * @param email
	 * @returns {boolean}
	 */
	static checkCardNo(email) {
		let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
		return reg.test(email);
	}
 
	/**
	 * 校验值长度 不少于6位数
	 * @param email
	 * @returns {boolean}
	 */
	static checkValueLength(password, min = 6, max = 0) {
		let regExp = new RegExp(`^[\\s\\S]{${min || ''},${max || ''}}$`);
		return regExp.test(password);
	}
 
	/**
	 * 电话号码加密   15288889999 转化为 152****9999
	 */
	static phoneEncryption(phone = "") {
		return phone.replace(/^(\d{3})\d{4}(\d+)/, '$1****$2')
	}
 
	/**
	 * 身份证号码加密
	 */
	static idCardEncryption(idCard) {
		if (!idCard) return ""
		let reg = /^(.{6})(?:\d+)(.{4})$/
		let result = idCard.replace(reg, '\$1******\$2') // 身份证号脱敏，将中间8位替换为“*”
		return result
	}
 
	/**验证输入重量、金额等类型   例如 0.11  2.23  100.123等等   
	 * @param {Object} value
	 */
	static checkMoney(value, len = 6) {
		let reg = /\d{1,}\.{0,1}\d{0,2}/;
		if (value.replace(reg, '')) {
			value = (value.match(reg) == null ? '' : value.match(reg));
		}
		if ((value >= 1) && (`${value}`.indexOf(0) == 0)) {
			value = parseFloat(value);
		}
		if (`${value}`.indexOf('00') == 0) {
			value = 0;
		}
		let str = parseInt(value).toString();
		if (str.length >= len && (value.toString().indexOf('.') < 0)) {
			value = parseFloat(str.slice(0, len));
		}
		return value;
	}
 
	/**验证输入的钱    单纯验证金额类型 
	 * @param {Object} value
	 */
	static isMoney(value) {
		var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
		if (reg.test(value)) {
			return true;
		} else {
			return false;
		};
	}
 
	// 验证是否是纯数值   
	static isNumber(value) {
		var reg = /^[0-9]*[1-9][0-9]*$/;
		if (reg.test(value)) {
			return true;
		} else {
			return false;
		};
	}
 
	/**
	 * 处理数据 ：可把制定相同的key值得对象存储到下级得children中
	 */
	static mergeData(list = [], key, name = 'children') {
		const data = [];
		list.forEach((item, index) => {
			const parent = data.find((i) => i[key] === item[key]);
			if (parent) {
				parent[name].push({
					...item
				});
			} else {
				let obj = {
					...item
				};
				if (!obj[name]) {
					obj[name] = [];
				}
				obj[name].push({
					...item
				});
				data.push(obj);
			}
		});
		return data;
	}
 
	// 表单验证   
	static validateForm(key, rules) {
		var check = true
		rules[key].forEach((v) => {
			// 验证失败
			if (!(v.rule).test(this[key])) {
				uni.showToast({
					title: v.msg,
					icon: 'none'
				});
				check = false
				return false
			}
		})
		return check
	};
 
	// uniapp 获取到上一页的信息,    适用：添加、编辑数据的时候，刷新上一页列表的数据  
	static beforePage(num = 1) {
		// 当前页的数据，
		let pages = getCurrentPages();
		// 上一页的数据
		let prevPage = pages[pages.length - (num + 1)];
		return prevPage.$vm;
	};
 
	//生成唯一ID  ：  根据当前系统时间随机生成一个长字符串
	static getID() {
		const now = new Date()
		const year = now.getFullYear();
		let month = now.getMonth() + 1;
		let day = now.getDate();
		let hour = now.getHours();
		let minutes = now.getMinutes();
		let seconds = now.getSeconds();
 
		month = month < 10 ? '0' + month : month;
		day = day < 10 ? '0' + day : day;
		hour = hour < 10 ? '0' + hour : hour;
		minutes = minutes < 10 ? '0' + minutes : minutes;
		seconds = seconds < 10 ? '0' + seconds : seconds;
 
		const yyyyMMddHHmmss = `${year}${month}${day}${hour}${minutes}${seconds}`;
		const rand = Math.random().toString(10).substr(2, 10);
 
		return `${yyyyMMddHHmmss}${rand}`;
	};
 
	//数字转中文  运行结果 ： 1 转为 一
	static toChinesNum(num) {
		let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
		let unit = ['', '十', '百', '千', '万']
		num = parseInt(num)
		let getWan = (temp) => {
			let strArr = temp.toString().split('').reverse()
			let newNum = ''
			let newArr = []
			strArr.forEach((item, index) => {
				newArr.unshift(item === '0' ? changeNum[item] : changeNum[item] + unit[index])
			})
			let numArr = []
			newArr.forEach((m, n) => {
				if (m !== '零') numArr.push(n)
			})
			if (newArr.length > 1) {
				newArr.forEach((m, n) => {
					if (newArr[newArr.length - 1] === '零') {
						if (n <= numArr[numArr.length - 1]) {
							newNum += m
						}
					} else {
						newNum += m
					}
				})
			} else {
				newNum = newArr[0]
			}
			return newNum
		}
		let overWan = Math.floor(num / 10000)
		let noWan = num % 10000
		if (noWan.toString().length < 4) {
			noWan = '0' + noWan
		}
		return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num)
	};
	// 图片转为base64
	static getBase64Image = (url, callback) => {
		// #ifdef MP-WEIXIN
		uni.getFileSystemManager().readFile({
			filePath: url, //选择图片返回的相对路径
			encoding: 'base64', //编码格式
			success: res => { //成功的回调
				console.log(res, '返回结果');
				let base64 = 'data:image/jpeg;base64,' + res.data //不加上这串字符，在页面无法显示的哦
				callback && callback(base64)
			},
			fail: (e) => {
				console.log("图片转换失败");
			}
		})
		// #endif
		// #ifdef H5
		uni.request({
			url: url,
			method: 'GET',
			responseType: 'arraybuffer',
			success: res => {
				let base64 = uni.arrayBufferToBase64(res.data); //把arraybuffer转成base64
				base64 = 'data:image/jpeg;base64,' + base64;
				callback && callback(base64)
			},
			fail: (e) => {
				console.log("图片转换失败");
			}
		})
		// #endif
		// #ifdef APP-PLUS
		plus.io.resolveLocalFileSystemURL(url, (entry) => {
			entry.file((file) => {
				let fileReader = new plus.io.FileReader();
				fileReader.onloadend = (e) => {
					callback && callback(e.target.result)
				};
				fileReader.readAsDataURL(file);
			})
		})
		// #endif
	};
	// 获取随机字符串
	static generateRandomString(length = 32) {
		const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
		let result = '';
		for (let i = 0; i < length; i++) {
			result += characters.charAt(Math.floor(Math.random() * characters.length));
		}
		return result;
	};
	// 授权微信小程序消息推送
	static authAppletInfoPush(tmplIdsArr = [], callback) {
		uni.requestSubscribeMessage({
			provider: 'weixin',
			tmplIds: tmplIdsArr,
			success: function(res) {
				console.log('success', res)
			},
			fail: function() {
				console.log('fail', res)
			},
			complete: function(res) {
				console.log('complete', res)
				if (callback) callback(res)
			}
		})
	}
}